<?php

class Listing_Form_PostAnAddCarForm extends Listing_Form_PostAnAddForm {

    private $_preview_link = '';
    private $_category;
    private $_adid;
    private $_listing;
    protected $elementButtonDecorators = array(
        'ViewHelper',
        'Errors',
    );
    protected $elementDecorators = array(
        'ViewHelper',
    );
    protected $formDecorators = array(
        'PrepareElements',
        array('ViewScript', array('viewScript' => 'index/customization/car-post-an-ad.phtml'))
    );
    protected $subFormDecorators = array(
        'FormElements',
        array('Description', array('placement' => 'prepend')),
        'fieldset',
    );
    protected $spanDecorators = array(
        'ViewHelper',
        'Errors',
        array('Label', array('placement' => 'prepend')),
        array(array('row' => 'HtmlTag'), array('tag' => 'span')),
    );
    protected $displayGroupDecorators = array(
        'FormElements',
        array('HtmlTag', array('tag' => 'p', 'class' => 'price radio text')),
        array('Description', array('placement' => 'prepend', 'tag' => 'label')),
    );
    protected $elementCheckBoxDecorators = array(
        'ViewHelper',
        'Errors',
        array('Label', array('placement' => 'APPEND')),
        array(array('row' => 'HtmlTag'), array('tag' => 'span')),
    );
    protected $elementMultiCheckBoxDecorators = array(
        'ViewHelper',
        'Errors',
    );
    protected $elementSelectDecorators = array(
        'ViewHelper',
        'Errors',
        array('Label', array()),
        array(array('row' => 'HtmlTag'), array('class' => 'select')),
    );

    public function __construct($options = array()) {
        $this->_preview_link = !empty($options['preview_link']) ? $options['preview_link'] : '';
        $this->_category = !empty($options['category']) ? $options['category'] : array();
        $this->_adid = !empty($options['adid']) ? $options['adid'] : array();
        $this->_listing = !empty($options['listing']) ? $options['listing'] : new StdClass();
        parent::__construct();
    }

    public function init() {
        parent::init();
        $element = new Zend_Form_Element_Hidden('adid');
        $element->setValue((string) $this->_adid);
        $element->setDecorators(array(
            'ViewHelper'
                )
        );
        $this->addElement($element);

        $i = 0;
        foreach ($this->_category as $cat) {
            $i++;
            $element = new Zend_Form_Element_Hidden('category_link' . $i);
            $element->setValue((string) $cat->_id);
            $element->setDecorators(array(
                'ViewHelper'
                    )
            );
            $this->addElement($element);
        }
        $cat_str = '<ul>';
        foreach ($this->_category as $cat_id) {
            $cat_str .= '<li>';
            $tmp = array();
            $category = Model_Category::find($cat_id->_id);
            foreach ($category->getParentTree() as $cat) {
                $tmp[] = $cat->name;
            }
            $cat_str .= implode(' > ', $tmp);
            $cat_str .= '</li>';
        }
        $cat_str .= '</ul>';
        $this->setDescription($cat_str);

        //Title
        $this->addElement('text', 'tl_en', array(
            'validators' => array(
                array('NotEmpty', true, array('messages' => '标题不足6个字')),
            ),
            'decorators' => $this->elementDecorators,
            'required' => true,
        ));

        // Make
        $make = Model_Listing_Car::getMakePostAd();
        $selected_make = empty($_POST['make']) ? 0 : $_POST['make'];
        if (!empty($this->_listing->make) && empty($_POST['make'])) {
            $selected_make = $this->_listing->make->_id;
        }
        if (empty($selected_make)) {
            reset($make);
            $selected_make = key($make);
        }
        //echo "<pre>";print_r((string)$this->_listing->model->_id);echo "</pre>";
        $this->addElement('select', 'make', array(
            'filters' => array('StringTrim'),
            'validators' => array(
                array('NotEmpty', true, array('messages' => '请选择汽车品牌/制造商')),
            ),
           	'disableLoadDefaultDecorators' => true,
            'decorators' => $this->elementDecorators,
            'multiOptions' => $make,
            'required' => true,
        ));

        // Model
        //echo "<pre>";print_r(Model_Listing_Car::getModelPostAd($this->_listing->make->_id));echo "</pre>";
        $this->addElement('select', 'model', array(
            //'filters'    => array('StringTrim'),
            'validators' => array(
                array('NotEmpty', true, array('messages' => '请选择车系')),
            ),
            'disableLoadDefaultDecorators' => true,
            'decorators' => $this->elementDecorators,
            'multiOptions' => Model_Listing_Car::getModelPostAd($selected_make),
            'required' => true,
        ));

        // Car Type
        $this->addElement('select', 'cartype', array(
            'filters' => array('StringTrim'),
            'validators' => array(
                array('NotEmpty', true, array('messages' => '请填写车型')),
            ),
            'disableLoadDefaultDecorators' => true,
            'decorators' => $this->elementDecorators,
            'multiOptions' => Model_Listing_Car::getCarTypePostAd(),
            'required' => true,
        ));

        // Year Manufactured
        $this->addElement('select', 'yearmanufactured', array(
            'filters' => array('StringTrim'),
            'validators' => array(
                array('NotEmpty', true, array('messages' => '请选择年份')),
            ),
            'disableLoadDefaultDecorators' => true,
            'decorators' => $this->elementDecorators,
            'multiOptions' => Model_Listing_Car::getYearManufacturedPostAd(),
            'required' => true,
        ));
        
        // transmission
        $this->addElement('select', 'transmission', array(
            'filters' => array('StringTrim'),
            'validators' => array(
                array('NotEmpty', true, array('messages' => '请选择变速箱类型')),
            ),
            'disableLoadDefaultDecorators' => true,
            'decorators' => $this->elementDecorators,
            'multiOptions' => Model_Listing_Car::getTransmissionPostAd(),
            'required' => false,
        ));
		/*
        $this->addElement('hidden', 'add_more_checkbox', array(
            'filters' => array('StringTrim', 'StringToLower'),
            'validators' => array(
            ),
            'disableLoadDefaultDecorators' => true,
            'decorators' => array(
                'ViewHelper',
                'Errors',
                array(array('data' => 'HtmlTag'), array('style' => 'display:none')),
            ),
            'value' => 1,
            'required' => false,
        ));

        // No of Previous Owners
        $this->addElement('select', 'previousowners', array(
            'filters' => array('StringTrim'),
            'validators' => array(
                array('NotEmpty', true, array('messages' => 'This information is required')),
            ),
            'decorators' => array(
                'ViewHelper',
                'Errors',
                array('Label', array()),
            //array(array('row' => 'HtmlTag'), array('class'=>'select')),
            ),
            'multiOptions' => Model_Listing_Car::getPreviousOwnersPostAd(),
            'required' => true,
        ));*/

        // Price
        $this->addElement('text', 'saleprice', array(
            'filters' => array('StringTrim', 'StringToLower'),
            'validators' => array(
                array('NotEmpty', true, array('messages' => '请填写价格 (只能用数字）')),
                array('Int', true, array('messages' => '仅能填写数字')),
            ),
            'disableLoadDefaultDecorators' => true,
            'decorators' => $this->elementDecorators,
            'required' => true,
        ));

        /*/ Capacity
        $this->addElement('text', 'capacity', array(
            'filters' => array('StringTrim', 'StringToLower'),
            'validators' => array(
                array('NotEmpty', true, array('messages' => 'This information is required')),
                array('Int', true, array('messages' => 'Numbers Only')),
            ),
            'disableLoadDefaultDecorators' => true,
            'decorators' => $this->elementDecorators,
            'required' => true,
        ));*/

        //Description
        $this->addElement('textarea', 'cs_en', array(
            'filters' => array('StringTrim'),
            'validators' => array(
                array('NotEmpty', true, array('messages' => '请填写补充说明')),
            ),
            'decorators' => $this->elementDecorators,
            'cols' => '80',
            'required' => true,
            'label' => 'Description:',
        ));

        /*/ Doors
        $this->addElement('radio', 'doors', array(
            //'filters'    => array('StringTrim', 'StringToLower'),
            'validators' => array(
            //'EmailAddress',
            ),
            'multioptions' => Model_Listing_Car::getDoorsPostAd(),
            'disableLoadDefaultDecorators' => true,
            'decorators' => $this->elementMultiCheckBoxDecorators,
            'required' => false,
        ));

        // Power Options
        $this->addElement('multiCheckbox', 'poweroptions', array(
            //'filters'    => array('StringTrim', 'StringToLower'),
            'validators' => array(
            //'EmailAddress',
            ),
            'multioptions' => Model_Listing_Car::getPowerOptionsPostAd(),
            'disableLoadDefaultDecorators' => true,
            'decorators' => $this->elementMultiCheckBoxDecorators,
            'required' => false,
        ));

        // Drive Type
        $this->addElement('radio', 'drivetype', array(
            //'filters'    => array('StringTrim', 'StringToLower'),
            'validators' => array(
            //'EmailAddress',
            ),
            'multioptions' => Model_Listing_Car::getDriveTypePostAd(),
            'disableLoadDefaultDecorators' => true,
            'decorators' => $this->elementMultiCheckBoxDecorators,
            'required' => false,
        ));

        // Engine
        $this->addElement('radio', 'engine', array(
            //'filters'    => array('StringTrim', 'StringToLower'),
            'validators' => array(
            //'EmailAddress',
            ),
            'multioptions' => Model_Listing_Car::getEnginePostAd(),
            'disableLoadDefaultDecorators' => true,
            'decorators' => $this->elementMultiCheckBoxDecorators,
            'required' => false,
        ));

        // Transmission
        $this->addElement('radio', 'transmission', array(
            //'filters'    => array('StringTrim', 'StringToLower'),
            'validators' => array(
            //'EmailAddress',
            ),
            'multioptions' => Model_Listing_Car::getTransmissionPostAd(),
            'disableLoadDefaultDecorators' => true,
            'decorators' => $this->elementMultiCheckBoxDecorators,
            'required' => false,
        ));

        // Fuel Economy
        $this->addElement('radio', 'fueleconomy', array(
            //'filters'    => array('StringTrim', 'StringToLower'),
            'validators' => array(
            //'EmailAddress',
            ),
            'multioptions' => Model_Listing_Car::getFuelEconomyPostAd(),
            'disableLoadDefaultDecorators' => true,
            'decorators' => $this->elementMultiCheckBoxDecorators,
            'required' => false,
        ));

        // Fuel
        $this->addElement('radio', 'fuel', array(
            //'filters'    => array('StringTrim', 'StringToLower'),
            'validators' => array(
            //'EmailAddress',
            ),
            'multioptions' => Model_Listing_Car::getFuelPostAd(),
            'disableLoadDefaultDecorators' => true,
            'decorators' => $this->elementMultiCheckBoxDecorators,
            'required' => false,
        ));

        */// Exterior Color
        $this->addElement('select', 'extcolor', array(
            'filters' => array('StringTrim'),
            'validators' => array(
                array('NotEmpty', true, array('messages' => '请选择颜色')),
            ),
            'multiOptions' => Model_Listing_Car::getColorPostAd(),
            'disableLoadDefaultDecorators' => true,
            'decorators' => $this->elementDecorators,
            'required' => true,
        ));

        /*/ Interior Color
        $this->addElement('multiCheckbox', 'intcolor', array(
            //'filters'    => array('StringTrim', 'StringToLower'),
            'validators' => array(
            //'EmailAddress',
            ),
            'multioptions' => Model_Listing_Car::getColorPostAd(),
            'disableLoadDefaultDecorators' => true,
            'decorators' => $this->elementMultiCheckBoxDecorators,
            'required' => false,
        ));

        // Safety Features
        $this->addElement('multiCheckbox', 'safetyfeatures', array(
            //'filters'    => array('StringTrim', 'StringToLower'),
            'validators' => array(
            //'EmailAddress',
            ),
            'multioptions' => Model_Listing_Car::getSafetyFeaturesPostAd(),
            'disableLoadDefaultDecorators' => true,
            'decorators' => $this->elementMultiCheckBoxDecorators,
            'required' => false,
        ));

        // Entertainment Communicaton Features
        $this->addElement('multiCheckbox', 'entertcomm', array(
            //'filters'    => array('StringTrim', 'StringToLower'),
            'validators' => array(
            //'EmailAddress',
            ),
            'multioptions' => Model_Listing_Car::getEntertCommPostAd(),
            'disableLoadDefaultDecorators' => true,
            'decorators' => $this->elementMultiCheckBoxDecorators,
            'required' => false,
        ));*/

        // Mileage
        $this->addElement('text', 'mileage', array(
            //'filters'    => array('StringTrim', 'StringToLower'),
            'validators' => array(
                array('NotEmpty', true, array('messages' => '请填写行驶里程 (只能用数字）')),
                array('Int', true, array('messages' => '仅能填写数字')),
            ),
            'decorators' => $this->elementDecorators,
            'required' => true,
        ));

        /*/ Horsepower
        $this->addElement('text', 'horsepower', array(
            //'filters'    => array('StringTrim', 'StringToLower'),
            'validators' => array(
                array('Int', true, array('messages' => 'Numbers Only')),
            ),
            'disableLoadDefaultDecorators' => true,
            'decorators' => $this->elementMultiCheckBoxDecorators,
            'required' => false,
        ));

        $this->addElement('textarea', 'st_en', array(
            'filters' => array('StringTrim'),
            'validators' => array(
                array('NotEmpty', true, array('messages' => 'This information is required')),
            ),
            'decorators' => $this->elementDecorators,
            'rows' => '',
            'required' => false,
        ));*/

        $areas = Model_Location::getAreaL1PostAd();
        if (empty($_POST['area_l1'])) {
            $selected_area = 0;
            if (!empty($this->_listing)) {
                $selected_area = '';
                if (empty($selected_area)) {
                    $loc = $this->_listing->area_l2;
                    if (!empty($loc)) {
                        $selected_area = (string) $loc->getParent()->_id;
                    }
                }
            }
        } else {
            $selected_area = $_POST['area_l1'];
        }
        if (empty($selected_area)) {
            reset($areas);
            $selected_area = key($areas);
        }
        $this->addElement('select', 'area_l1', array(
            'filters' => array('StringTrim'),
            'validators' => array(
                array('NotEmpty', true, array('messages' => 'This information is required')),
            ),
            'multiOptions' => $areas,
            'disableLoadDefaultDecorators' => true,
            'decorators' => $this->elementDecorators,
            'required' => true,
        ));

        //District
        $this->addElement('select', 'area_l2', array(
            'filters' => array('StringTrim'),
            'validators' => array(
                array('NotEmpty', true, array('messages' => 'This information is required')),
            ),
            'multiOptions' => Model_Location::getAreaL2PostAd($selected_area),
            'disableLoadDefaultDecorators' => true,
            'decorators' => $this->elementDecorators,
            'required' => false,
        ));
        //$this->getElement('area_l2')->setOptions(array('disabled' => 'disabled'));
        
        //location flag
        $this->addElement('radio', 'loc_flag', array(
            'filters'    => array('StringTrim', 'StringToLower'),
            'validators' => array(
                //'Int'
            ),
            'multiOptions' => array(
                'chi' => '中国+香港+澳门',
                'mchi' => '中国大陆',
            ),
            'separator' => '',
            //'value' => '0',
            'disableLoadDefaultDecorators' => true,
            'decorators' => $this->elementDecorators,
            'required'   => false,
        ));
        
		
		$this->addElement('text', 'st_en', array(
       	 	'filters'    => array('StringTrim'),
            'validators' => array(
                array('NotEmpty', true, array('messages' => 'This information is required')),                
            ),
            'decorators' => $this->elementDecorators,
            'required'   => false,
            'label'      => 'Street address:',
        ));
        
        $this->addElement('text', 'displacement', array(
            'validators' => array(
                array('NotEmpty', true, array('messages' => '请填写排量')),        
				array('Int', true, array('messages' => '仅能填写数字')),        
            ),
            'decorators' => $this->elementDecorators,
            //'decorators' => array_merge($this->elementDecorators, array(array(array('row' => 'HtmlTag'), array('tag' => 'p', 'class' => 'title text')))),
            'required'   => false,
            'label'      => 'Displacement:',
        ));
        
        $this->addElement('checkbox', 'brandsale', array(
            'filters'    => array('StringTrim', 'StringToLower'),
            'validators' => array(
            ),
            'disableLoadDefaultDecorators' => true,
            'decorators' => $this->elementDecorators,
            'required'   => false,
        ));
        
        $this->addElement('text', 'tag', array(
            'validators' => array(
                //array('NotEmpty', true, array('messages' => 'This information is required')),                
            ),
            'decorators' => $this->elementDecorators,
            //'decorators' => array_merge($this->elementDecorators, array(array(array('row' => 'HtmlTag'), array('tag' => 'p', 'class' => 'title text')))),
            'required'   => false,
            'label'      => 'Tag:',
        ));
        
        $this->addElement('text', 'remark', array(
            'validators' => array(
                //array('NotEmpty', true, array('messages' => 'This information is required')),                
            ),
            'decorators' => $this->elementDecorators,
            //'decorators' => array_merge($this->elementDecorators, array(array(array('row' => 'HtmlTag'), array('tag' => 'p', 'class' => 'title text')))),
            'required'   => false,
            'label'      => 'Remark:',
        ));
        
        $this->addElement('text', 'c_name', array(
            'validators' => array(
                //array('NotEmpty', true, array('messages' => 'This information is required')),                
            ),
            'decorators' => $this->elementDecorators,
            //'decorators' => array_merge($this->elementDecorators, array(array(array('row' => 'HtmlTag'), array('tag' => 'p', 'class' => 'title text')))),
            'required'   => false,
            'label'      => 'Contact Name:',
        ));
        
        $this->addElement('checkbox', 'agent', array(
            'filters'    => array('StringTrim', 'StringToLower'),
            'validators' => array(
            ),
            'disableLoadDefaultDecorators' => true,
            'decorators' => $this->elementDecorators,
            'required'   => false,
        ));
        
        $this->addElement('text', 'c_tel', array(
            'validators' => array(
                //array('NotEmpty', true, array('messages' => 'This information is required')),                
            ),
            'decorators' => $this->elementDecorators,
            //'decorators' => array_merge($this->elementDecorators, array(array(array('row' => 'HtmlTag'), array('tag' => 'p', 'class' => 'title text')))),
            'required'   => false,
            'label'      => 'Contact Tel:',
        ));
        
        $this->addElement('text', 'c_msn', array(
            'validators' => array(
                //array('NotEmpty', true, array('messages' => 'This information is required')),                
            ),
            'decorators' => $this->elementDecorators,
            //'decorators' => array_merge($this->elementDecorators, array(array(array('row' => 'HtmlTag'), array('tag' => 'p', 'class' => 'title text')))),
            'required'   => false,
            'label'      => 'MSN / QQ:',
        ));
		
        $this->addElement('button', 'validate', array(
            'required' => false,
            'ignore' => true,
            'type' => 'submit',
            'label' => 'Post your ad',
            'decorators' => array_merge($this->elementButtonDecorators, array(array(array('row' => 'HtmlTag'), array('tag' => 'p', 'class' => 'button_em')))),
        ));

        $this->addElement('button', 'preview', array(
            'required' => false,
            'ignore' => true,
            'type' => 'button',
            'label' => 'Preview',
            //'description' => '<a href="'.$this->_preview_link.'">Preview</a>',
            'decorators' => array_merge($this->elementButtonDecorators, array(array(array('row' => 'HtmlTag'), array('tag' => 'p', 'class' => 'preview button')))),
        ));

        $opt = $this->getDecorator('ViewScript')->getOptions();
        $opt['category'] = $this->_category;
        $opt['adid'] = $this->_adid;
        $opt['listing'] = $this->_listing;
        $opt['preview_link'] = $this->_preview_link;

        $this->getDecorator('ViewScript')->setOptions($opt);
    }

    public function populate(array $arr) {
        //echo "<PRE>";
        //print_r($arr);
        //exit;
        //
    // Required
        //Title
        // if (empty($arr['tl_en'])) {
        // $this->getElement('tl_en')->setValue($this->_listing->tl_en);
        // }
        //Description
        // if (empty($arr['cs_en'])) {
        // $this->getElement('cs_en')->setValue($this->_listing->cs_en);
        // }

        if (Zend_Registry::get('current_language') == 'en') {
            $ft = 'en';
            $tt = 'zh-TW';

            $this->getElement('tl_en')->setValue($this->_listing->tl_en);
            $this->getElement('cs_en')->setValue($this->_listing->cs_en);
            $this->getElement('st_en')->setValue((string) $this->_listing->st_en);
        } else {
            $ft = 'zh-TW';
            $tt = 'en';

            $this->getElement('tl_en')->setValue($this->_listing->tl_sc);
            $this->getElement('cs_en')->setValue($this->_listing->cs_sc);
            $this->getElement('st_en')->setValue((string) $this->_listing->st_sc);
        }

        //Price
        if (empty($arr['saleprice'])) {
            $this->getElement('saleprice')->setValue($this->_listing->price);
        }
        //displacement
        if (empty($arr['displacement'])) {
            $this->getElement('displacement')->setValue($this->_listing->displacement);
        }
        //brand sale
        if (empty($arr['brandsale'])) {
            $this->getElement('brandsale')->setValue((string) $this->_listing->brandsale);
        }
        //Make
        if (empty($arr['make'])) {
            if (is_object($this->_listing->make)) {
                $str = $this->_listing->make->name;
            } else {
                $str = $this->_listing->make;
            }
            $this->getElement('make')->setValue((string) $str);
        }
        //Model
        if (empty($arr['model'])) {
            if (is_object($this->_listing->model)) {
                $str = $this->_listing->model->name;
            } else {
                $str = $this->_listing->model;
            }
            $this->getElement('model')->setValue((string) $str);
        }
        /*/Capacity
        if (empty($arr['capacity'])) {
            $this->getElement('capacity')->setValue((string) $this->_listing->capacity);
        }*/
        //Year Manufactured
        if (empty($arr['yearmanufactured'])) {
            $this->getElement('yearmanufactured')->setValue((string) $this->_listing->yearmanufactured);
        }
        //Car Type
        if (empty($arr['cartype'])) {
            $this->getElement('cartype')->setValue((string) $this->_listing->cartype);
        }
        /*/Number of Previous Owner
        if (empty($arr['previousowners'])) {
            $this->getElement('previousowners')->setValue((string) $this->_listing->nopreviousowners);
        }*/
        //Area
        if (empty($arr['area_l1'])) {
            $selected_area = '';
            if (empty($selected_area)) {
                $loc = $this->_listing->area_l2;
                if (!empty($loc)) {
                    $selected_area = (string) $loc->getParent()->_id;
                }
            }
            $this->getElement('area_l1')->setValue((string) $selected_area);
        }
        //District
        if (empty($arr['area_l2'])) {
            if (isset($this->_listing->area_l2->_id)) {
                $this->getElement('area_l2')->setValue((string) $this->_listing->area_l2->_id);
            }
        }
        //Street
        // if (empty($arr['street'])) {
        // $this->getElement('address')->setValue((string)$this->_listing->street);
        // }
        //Optional
        /*/Doors
        if (empty($arr['doors'])) {
            $this->getElement('doors')->setValue((string) $this->_listing->doors);
        }
        //ower Options
        if (empty($arr['poweroptions'])) {
            $this->getElement('poweroptions')->setValue((array) $this->_listing->poweroptions);
        }
        //Entertainment Communication Features
        if (empty($arr['entertainmentfeatures'])) {
            $this->getElement('entertcomm')->setValue((array) $this->_listing->entertainmentfeatures);
        }
        //Safety Features
        if (empty($arr['safetyfeatures'])) {
            $this->getElement('safetyfeatures')->setValue((array) $this->_listing->safetyfeatures);
        }
        //Interior Color
        if (empty($arr['interiorcolor'])) {
            $this->getElement('intcolor')->setValue((array) $this->_listing->interiorcolor);
        }*/
        //Exterior Color
        if (empty($arr['extcolor'])) {
            $this->getElement('extcolor')->setValue((string) $this->_listing->exteriorcolor);
        }
        /*/Drive Type
        if (empty($arr['drivetype'])) {
            $this->getElement('drivetype')->setValue((string) $this->_listing->drivetype);
        }
        //Horsepower
        if (empty($arr['horsepower'])) {
            $this->getElement('horsepower')->setValue((string) $this->_listing->horsepower);
        }
        //Engine
        if (empty($arr['engine'])) {
            $this->getElement('engine')->setValue((string) $this->_listing->engine);
        }*/
        //Mileage
        if (empty($arr['mileage'])) {
            $this->getElement('mileage')->setValue((string) $this->_listing->mileage);
        }
        //Transmission
        if (empty($arr['transmission'])) {
            $this->getElement('transmission')->setValue((string) $this->_listing->transmission);
        }
        /*/Fuel Economy
        if (empty($arr['fueleconomy'])) {
            $this->getElement('fueleconomy')->setValue((string) $this->_listing->fueleconomy);
        }
        //Fuel
        if (empty($arr['fuel'])) {
            $this->getElement('fuel')->setValue((string) $this->_listing->fuel);
        }*/
        //agent
		if (empty($arr['agent'])) {
            $this->getElement('agent')->setValue((string) $this->_listing->agent);
        }
		
		if (empty($arr['tag'])) {
        	if(!empty($this->_listing->tags)){
				$this->getElement('tag')->setValue(implode(',', $this->_listing->tags));
			}            
        }
        
        if (empty($arr['remark'])) {
            $this->getElement('remark')->setValue((string)$this->_listing->remark);
        }
        
        if (empty($arr['c_name'])) {
            $this->getElement('c_name')->setValue((string)$this->_listing->c_name);
        }
        
        if (empty($arr['c_tel'])) {
            $this->getElement('c_tel')->setValue((string)$this->_listing->c_tel);
        }
        
        if (empty($arr['c_msn'])) {
            $this->getElement('c_msn')->setValue((string)$this->_listing->c_msn);
        }
        parent::populate($arr);
        return $arr;
    }

    public function save($preview = false) {
        if (empty($this->_adid)) {
            $ad = new Model_Listing_Regular();
        } else {
            $ad = Model_Listing_Preview::find(new MongoId($this->_adid));
        }
        //$this->_category = Model_Listing_Preview::fixCategories($this->_category);

        if (Zend_Registry::isRegistered('loggedin_user')) {
            $user = Zend_Registry::get('loggedin_user');
            if ($user->role == Model_User::ROLE_ADMIN) {
                if (empty($ad->us)) {
                    $ad->user = $user->_id;
                }
            } else {
                $ad->user = $user->_id;
            }
            if (empty($this->status)) {
                $ad->status = Model_Listing::STATUS_PUBLISHED;
            }
        } else {
            $ad->status = 6;
        }

        $classname = Model_Listing::getInstanceClassname((array) $this->_listing->ca);
        $translateFields = $classname::getTranslationFormField();

        $this->translate($ad, $translateFields, $classname);

        //print_r($ad);exit;
        //Requiered Attributs
        // $ad->title               = $_POST['title'];
        // $ad->description         = $_POST['description'];

        /* $gt = new Ac_Translation();
          $gt2 = new Ac_Translation();
          $gt3 = new Ac_Translation();

          if (Zend_Registry::get('current_language') == 'en'){
          $ad->ad_type = 1;
          $ft = 'en';
          $tt = 'zh-TW';
          $ad->title_en       = $POST['title'];
          $ad->description_en = $POST['description'];
          $ad->street     = $POST['address'];

          $ad->title_tc = $gt->translate($POST['title'], $tt, $ft);
          $ad->description_tc = $gt2->translate($POST['description'], $tt, $ft);
          $ad->street_tc     = $gt3->translate($POST['address'], $tt, $ft);

          } else {
          $ad->ad_type = 2;
          $ft = 'zh-TW';
          $tt = 'en';
          $ad->title_tc       = $POST['title'];
          $ad->description_tc = $POST['description'];
          $ad->street_tc     = $POST['address'];

          $ad->title_en = $gt->translate($POST['title'], $tt, $ft);
          $ad->description_en = $gt2->translate($POST['description'], $tt, $ft);
          $ad->street    = $gt3->translate($POST['address'], $tt, $ft);

          } */

        //$ad->nopreviousowners = $_POST['previousowners'];
        $ad->make = new MongoId($_POST['make']);
        $ad->model = new MongoId($_POST['model']);
        $ad->price = $_POST['saleprice'];
        //$ad->capacity = (int) $_POST['capacity'];
        $ad->yearmanufactured = $_POST['yearmanufactured'];
        $ad->cartype = $_POST['cartype'];
        //$ad->street              = $_POST['address'];
        $ad->area_l1 = new MongoId($_POST['area_l1']);
        if ((string) $_POST['area_l1'] == ONLINE_ONLY_AREA) {
            $ad->area_l2 = new MongoId(ONLINE_ONLY_AREA);
        }
        elseif((string)$this->getValue('area_l1') == ENTIRE_CITY) {
            $ad->area_l2 = new MongoId(ENTIRE_CITY);
        } else {
            $ad->area_l2 = new MongoId($_POST['area_l2']);
        }

        /*/Optional Attributs
        if (!empty($_POST['doors'])) {
            $ad->doors = $_POST['doors'];
        }
        if (!empty($_POST['poweroptions'])) {
            $ad->poweroptions = $_POST['poweroptions'];
        }
        if (!empty($_POST['entertcomm'])) {
            $ad->entertainmentfeatures = $_POST['entertcomm'];
        }
        if (!empty($_POST['safetyfeatures'])) {
            $ad->safetyfeatures = $_POST['safetyfeatures'];
        }
        if (!empty($_POST['intcolor'])) {
            $ad->interiorcolor = $_POST['intcolor'];
        }*/
        if (!empty($_POST['extcolor'])) {
            $ad->exteriorcolor = $_POST['extcolor'];
        }
        /*if (!empty($_POST['drivetype'])) {
            $ad->drivetype = $_POST['drivetype'];
        }
        if (!empty($_POST['horsepower'])) {
            $ad->horsepower = $_POST['horsepower'];
        }
        if (!empty($_POST['engine'])) {
            $ad->engine = $_POST['engine'];
        }*/
        if (!empty($_POST['transmission'])) {
            $ad->transmission = $_POST['transmission'];
        }
        if (!empty($_POST['mileage'])) {
            $ad->mileage = $_POST['mileage'];
        }
        /*if (!empty($_POST['fueleconomy'])) {
            $ad->fueleconomy = $_POST['fueleconomy'];
        }
        if (!empty($_POST['fuel'])) {
            $ad->fuel = $_POST['fuel'];
        }*/

        if ($_GET['category'][0] == '4cda48368835c1d4132e0000') {
            //echo "<pre>";print_r($_GET['category'][0]);echo "</pre>";exit();
        }

        //Save the category related to this Ad
        foreach ($this->_category as $cat) {
            /*
              if ((string) $cat->id == 'f2b545a8abb14f8706f808a79277c061') { //car


              //echo "<pre>".(string)$cat->_id."</pre>";exit();
              if (Zend_Registry::isRegistered('loggedin_user')) {
              $user = Zend_Registry::get('loggedin_user');
              if ($user->type_account == 1) {
              $ad->category = new MongoId('4cda3e818835c16810630100');
              } elseif ($user->type_account == 6) {
              $ad->category = new MongoId('4cda3e818835c16810670100');
              }
              break;
              }
              }
             * 
             */
            $ad->addCategory($cat->_id);
        }
		$ad->tl_sc 			= (string)$this->getValue('tl_en');
        $ad->cs_sc 			= (string)$this->getValue('cs_en');
        $ad->st_sc 			= (string)$this->getValue('st_en');
        $ad->tag 			= (string)$this->getValue('tag');
        $ad->rmrk 			= (string)$this->getValue('remark');
        $ad->c_name 		= (string)$this->getValue('c_name');
        $ad->c_tel 			= (string)$this->getValue('c_tel');
        $ad->c_msn 			= (string)$this->getValue('c_msn');
        $ad->loc_flag 		= (string)$this->getValue('loc_flag');        
        $ad->agent = (string)$this->getValue('agent');
        
        if (!empty($_POST['displacement'])) {
            $ad->displacement = $_POST['displacement'];
        }
        if (!empty($_POST['brandsale'])) {
            $ad->brandsale = $_POST['brandsale'];
        }

        $this->continueFillup();
        if (!$preview) {
            $ad = Model_Listing_Preview::saveAsListing($ad);
            Model_Listing_Preview::remove(array('_id' => $ad->_id));
        } else {
            //$ad = Model_Listing_Preview::convertFromListing($ad);
            $ad->forceSave();
        }
        return $ad;
    }

    protected function continueFillup() {
        
    }

    public function __toString() {

        $str = '       	
            $j("#make").change(function (event) {
                event.stopImmediatePropagation();
                $j.get("/search/get-attribute", { c:"car", f:"postad", id: $j("#make").val() },
                    function(data) {
                        $j("#model").empty();
                        $j.each(data, function (index, value) {
                            $(document.createElement("option"))
                                .html(value)
                                .attr("value", index)
                                .appendTo($("#model"));
                        });
                    });
           });        
            $j("#area_l1").change(function (event) {                
                event.stopImmediatePropagation();
                $j.get("/search/get-attribute", { c:"area", f:"area_l2_postad", id: $j("#area_l1").val() },
                    function(data) {
                        $j("#area_l2").empty();
                        $j.each(data, function (index, value) {
                            $(document.createElement("option"))
                                .html(value)
                                .attr("value", index)
                                .appendTo($("#area_l2"));
                        });
                         //Entire City
					    if ($j("#area_l1").val() == "4eeae63be62d6c5978000000" || $j("#area_l1").val() == "4eeeeeeeeeeeeeeeeeeeeeee" || $j("#area_l1").val() == "4aaaaaaaaaaaaaaaaaaaaaaa") {
					        $j("#area_l2").hide();
					        $j("#st_en").hide();
					    }
					    else {
					        $j("#area_l2").show();
					        $j("#st_en").show();
					    }
                    });
           });
		   
        ';
        if (!empty($this->_listing->make->_id) && empty($_POST['make'])) {
            $str .= '
				$j("#make").val("' . $this->_listing->make->_id . '");
				$j("#model").val("' . $this->_listing->model->_id . '");
			';
        }
        $str2 = '
			$j("tl_tc_back").click(function(event) {
			alert("test");
   
			});
		
		';
        $this->view->JQuery()->addJavascript($str);
        $this->view->JQuery()->addJavascript($str2);
        return parent::__toString();
    }

    public function isValid($post = array()) {
        $test1 = parent::isValid($post);
        $test2 = true;

        //Check Bad Words in Title
        if ($match = Ac_Util::checkBadWord($_POST['tl_en'])) {
            $this->getElement('tl_en')->addError('请不要填写含有敏感词的信息');
            $test2 = false;
        }

        //Check Bad Words in Description
        if ($match = Ac_Util::checkBadWord($_POST['cs_en'])) {
            $this->getElement('cs_en')->addError('请不要填写含有敏感词的信息');
            $test2 = false;
        }

        //Regex Title contain Email Address
        if (preg_match("#.[a-z0-9._-]+@[a-z0-9._-]{2,}\.[a-z]{2,4}.#", $_POST['tl_en'])) {
            $test2 = false;
        }
        //Regex description contain Email Address
        if (preg_match("#.[a-z0-9._-]+@[a-z0-9._-]{2,}\.[a-z]{2,4}.#", $_POST['cs_en'])) {
            $test2 = false;
        }

        // We need to check manually these fields
        else {
            /* if (empty($post['dealername'])) {
              $this->getElement('dealername')->addError('This information is required');
              $test2 = false;
              }
              if (empty($post['dealerphone'])) {
              $this->getElement('dealerphone')->addError('This information is required');
              $test2 = false;
              }
              if (empty($post['dealeremail'])) {
              $this->getElement('dealeremail')->addError('This information is required');
              $test2 = false;
              } */
        }

        //Exception for Online Only for Area and District
        $data = Model_Location::one(array('_id' => new MongoId($post['area_l1'])));
        if (!empty($data)) {
            /*if ($data->nm_en != 'Online Only') {
                if (empty($post['district'])) {
                    $this->getElement('district')->addError('This information is required');
                    $test2 = false;
                }
            }*/
            if ($data->nm_sc != 'Entire City') {
                if (empty($post['area_l2'])) {
                    $this->getElement('area_l2')->addError('This information is required');
                    $test2 = false;
                }
            }
        }

        //Check the two validations
        if ($test1 & $test2) {
            return true;
        } else {
            return false;
        }
    }

}
